package model

import (
	"errors"
	"time"
)

type Paper struct {
	Id       int64 //`json:"-"`
	MinLevel int32 // user level limit
	Name     string
	Enable   bool
	Kind     string
	Organize string
	//Group      string
	CreatedAt  time.Time
	UpdatedAt  time.Time
	TotalScore int32
	PassScore  int32
	AvgScore   int32 // average score for user
	Duration   int32
	Describe   string
	Sids       []int64    `json:"-"`
	Sections   []*Section `xorm:"-"`
}

func (p *Paper) OneById() error {
	ok, err := orm.ID(p.Id).Get(p)
	if !ok {
		return errors.New(PaperNotFound)
	}
	return err
}

func (p *Paper) Create() error {
	p.Enable = true
	ok, err := orm.Insert(p)
	if ok == 0 {
		return errors.New(PaperCreateFailed)
	}
	return err
}

func (p *Paper) Count() (int64, error) {
	o := orm.Where("id > ?", 0)
	if p.Enable {
		o.Where("enable = ?", true)
	}
	return o.Count(p)
}

func (p *Paper) MaxID() (int64, error) {
	np := new(Paper)
	ok, err := orm.Desc("id").Get(np)
	if !ok {
		return 0, errors.New(PaperUpdateFailed)
	}
	return np.Id, err
}

func (p *Paper) Update() error {
	ok, err := orm.Id(p.Id).Cols("sids").Update(p)
	if ok == 0 {
		return errors.New(PaperUpdateFailed)
	}
	return err
}
